package com.zohnblog.service.impl;

import com.zohnblog.dao.WebStatisticMapper;
import com.zohnblog.model.domain.WebStatistic;
import com.zohnblog.service.IWebStatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class WebStatisticServiceImpl implements IWebStatisticService {
    @Autowired
    WebStatisticMapper webStatisticMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 创建新日期的统计
     */
    @Override
    public Integer addWebStatistic(WebStatistic webStatistic) {
        return webStatisticMapper.addWebStatistic(webStatistic);
    }

    /**
     * 如果date以存在,则更新数据库数据;
     * 若不存在,则创建一个
     */
    @Override
    public Integer addRequests(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(date);
        Object o = redisTemplate.opsForValue().get("webStatistic_" + dateStr);
        if (o != null) {
            return webStatisticMapper.addRequestsByDate(dateStr);
        } else {
            Integer requests = webStatisticMapper.addRequestsByDate(dateStr);
            if (requests != 0) {
                redisTemplate.opsForValue().set("webStatistic_" + dateStr, 1);
                return requests;
            } else {
                WebStatistic webStatistic = new WebStatistic();
                webStatistic.setDate(date);
                webStatistic.setRequests(1);
                redisTemplate.opsForValue().set("webStatistic_" + dateStr, 1);
                return addWebStatistic(webStatistic);
            }
        }
    }

    /**
     * 通过日期增加访问数
     */
    @Override
    public Integer getRequestsByDate(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(date);
        return webStatisticMapper.getRequestsByDate(dateStr);
    }
}
